package com.zou.lotterylucky.activity

import android.content.Intent
import android.os.Bundle
import com.android.volley.toolbox.Volley
import com.kaopiz.kprogresshud.KProgressHUD
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.v2.request.RequestCenter
import com.v2.utils.TToast
import com.v2.utils.okhttp.OkHttpRequestCallback
import com.zou.lotterylucky.Constants
import com.zou.lotterylucky.R
import com.zou.lotterylucky.utils.SPUtils
import com.zou.lotterylucky.utils.TLog
import com.zou.lotterylucky.utils.ToastUtil
import kotlinx.android.synthetic.main.activity_login.*
import org.json.JSONException
import org.json.JSONObject

class LoginActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        switchLangLbl.setOnClickListener {
            val current = SPUtils[Constants.SP_Lang, 1] as Int
            val opts = arrayOf("Spanish", "中文", "English")
            QMUIDialog.CheckableDialogBuilder(this)
                .setCheckedIndex(current)
                .addItems(opts) { d, index ->
                    d.dismiss()
                    SPUtils[this, Constants.SP_Lang] = index

                    val intent = Intent(this, LoginActivity::class.java)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                    startActivity(intent)
                    finish()
                }.create().show()
        }

        loginBtn.setOnClickListener {
            val username = usernameTxt.text.toString()

            if (username.isEmpty()) {
                ToastUtil.showMsg(this, R.string.input_username)
                return@setOnClickListener
            }

            val password = passwordTxt.text.toString()

            if (password.isEmpty()) {
                ToastUtil.showMsg(this, R.string.input_password)
                return@setOnClickListener
            }

            loginAction(username, password)
        }
    }

    private fun loginAction(username: String, password: String) {
//        val requestQueue = Volley.newRequestQueue(this)
//        val loginUrl = Constants.SERVER_URL + "login"
//        val params = JSONObject()
//        params.put("machine_number", username)
//        params.put("password", password)
        val hud = KProgressHUD.create(this).setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
            .setCancellable(true)
            .setAnimationSpeed(2)
            .setDimAmount(0.5f)
            .show()
        RequestCenter.login(username, password, object : OkHttpRequestCallback {
            override fun onSuccess(result: String?) {
                val response = JSONObject(result)
                //TLog.net("appLogin(), success:$result, data:${response.getBoolean("data")}")
                try {
                    hud.dismiss()
                    if (response.getString("code").equals("200")) {
                        SPUtils["remember_password"] = rememberPasswordCheck.isChecked
                        SPUtils["username"] = username
                        SPUtils["password"] = password
//                        val data = response.get("data") as JSONObject
//                        val limitsData = data.get("todayTimeLimit") as JSONArray
//                        timeLimits = mutableListOf()
//                        for (i in 0..3) {
//                            val timeLimit = TimeLimit(limitsData.getJSONObject(i))
//                            timeLimits.add(timeLimit)
//                        }
                        startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                    } else {
                        TToast.show(R.string.login_fail)
                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }

            override fun onFailure(error: String?) {
                hud.dismiss()
                TToast.show(R.string.login_fail)
                TLog.net("appLogin(), failure:$error")
            }
        })
    }

    override fun onResume() {
        super.onResume()

        if (SPUtils["remember_password", false] as Boolean) {
            usernameTxt.setText(SPUtils[this, "username", ""] as String)
            passwordTxt.setText(SPUtils[this, "password", ""] as String)
            rememberPasswordCheck.isChecked = true
        } else {
            usernameTxt.setText("")
            passwordTxt.setText("")
        }
    }
}